<template>
  <Form ref="formDom" :validation-schema="mySchema" v-slot="{ errors }" class="xtx-form" autocomplete="off">
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-user"></i>
        <Field :class="{ err: errors.account }" v-model="form.account" name="account" class="input" type="text"
          placeholder="请输入用户名" />
      </div>
      <div v-if="errors.account" class="error"><i class="iconfont icon-warning" />{{ errors.account }}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <Field :class="{ err: errors.mobile }" v-model="form.mobile" name="mobile" class="input" type="text"
          placeholder="请输入手机号" />
      </div>
      <div v-if="errors.mobile" class="error"><i class="iconfont icon-warning" />{{ errors.mobile }}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field :class="{ err: errors.code }" v-model="form.code" name="code" class="input" type="text"
          placeholder="请输入验证码" />
        <span class="code" @click="send">{{ countDown === 0 ? '发送验证码' : `${countDown}后重新发送` }} </span>
      </div>
      <div v-if="errors.code" class="error"><i class="iconfont icon-warning" />{{ errors.code }}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-lock"></i>
        <Field :class="{ err: errors.password }" v-model="form.password" name="password" class="input" type="password"
          placeholder="请输入密码" />
      </div>
      <div v-if="errors.password" class="error"><i class="iconfont icon-warning" />{{ errors.password }}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-lock"></i>
        <Field :class="{ err: errors.rePassword }" v-model="form.rePassword" name="rePassword" class="input"
          type="password" placeholder="请确认密码" />
      </div>
      <div v-if="errors.rePassword" class="error"><i class="iconfont icon-warning" />{{ errors.rePassword }}</div>
    </div>
    <a href="javascript:;" class="submit" @click="submit">立即提交</a>
  </Form>
</template>

<script lang="ts" setup>
import { Form, Field } from 'vee-validate'
import { reactive, ref, onUnmounted } from 'vue'
import schema from '../../utils/vee-validate-schema'
import { useIntervalFn } from '@vueuse/core'
import { userQQPatchCode, userQQPatchLogin } from '../../api/user'
import message from '../../components/library/message'
import { useRoute, useRouter } from 'vue-router'
import userStore from '../../store/index'
const props = defineProps({
  unionId: {
    type: String,
    default: ''
  }
})
// 表单验证对象
const form = reactive({
  account: null,
  mobile: null,
  code: null,
  password: null,
  rePassword: null
})
// 表单验证规则
const mySchema = {
  account: schema.accountApi,
  mobile: schema.mobile,
  code: schema.code,
  password: schema.password,
  rePassword: schema.rePassword
}
const formDom: any = ref(null)
/// pause 暂停 resume 开始
// useIntervalFn(回调函数,执行间隔,是否初始化立即开启)
// 设计一个倒计时
const countDown = ref(0)
const { pause, resume } = useIntervalFn(() => {
  countDown.value--
  if (countDown.value <= 0) {
    pause()
  }
}, 1000, { immediate: false })
// 销毁组件时销毁倒计时
onUnmounted(() => {
  pause()
})
// 1. 发送验证码
// 1.1 绑定发送验证码按钮点击事件
// 1.2 校验手机号，如果成功才去发送短信（定义API），请求成功开启60s的倒计时，不能再次点击，倒计时结束恢复
// 1.3 如果失败，失败的校验样式显示出来
const send = async () => {
  const valid = mySchema.mobile(form.mobile)
  // 验证通过
  if (valid) {
    // 倒计时事件已经过了,才可重新发送验证码
    if (countDown.value === 0) {
      await userQQPatchCode(form.mobile).catch(rej => {
        if (rej.response.status === 400) {
          message({ type: 'error', text: '用户不存在', countDown: 1500 })
        } else {
          message({ type: 'success', text: '发送成功', countDown: 1500 })
          countDown.value = 60
          resume()
        }
      }
      )
    }
  } else {
    // 验证不通过
    // 失败，使用vee的错误函数显示错误信息 setFieldError(字段,错误信息)
    formDom.value.setFieldError('mobile', valid)
  }
}
// 完善信息
const { user } = userStore()
const router = useRouter()
const route: any = useRoute()
const submit = async () => {
  const valid = formDom.value.validate()
  if (valid) {
    userQQPatchLogin({
      unionId: props.unionId,
      ...form
    }).then((res: any) => {
      // 实现和之前登录一样的逻辑
      // 1. 存储用户信息
      const { id, account, avatar, mobile, nickname, token } = res.result
      user.setUser({ id, account, avatar, mobile, nickname, token })
      // 2. 跳转到来源页或者首页
      // 3. 跳转要原来页或首页
      router.push(route.query.redirectUrl || '/')
      // 3. 成功提示
      message({ type: 'success', text: 'QQ完善信息成功', countDown: 1500 })
    }).catch(e => {
      message({ type: 'error', text: '完善信息失败', countDown: 1500 })
    })
  }
}
console.log(route.query.redirectUrl);
</script>

<style  lang='less' scoped>
@import '../../assets/styles/mixins.less';
@import '../../assets/styles/variables.less';

.code {
  position: absolute;
  right: 0;
  top: 0;
  line-height: 50px;
  width: 80px;
  color: #999;

  &:hover {
    cursor: pointer;
  }
}
</style>